import Vue from "vue";
import VueRouter from "vue-router";

const Login = () =>
  import(/* webpackChunkName: "login" */ "views/login/Login.vue");
const Home = () => import(/* webpackChunkName: "home" */ "views/home/Home.vue");
const Welcome = () =>
  import(
    /* webpackChunkName: "welcome" */ "views/home/childrenViews/Welcome.vue"
  );
const Users = () =>
  import(/* webpackChunkName: "users" */ "views/users/Users.vue");
const Rights = () =>
  import(/* webpackChunkName: "rights" */ "views/power/Rights.vue");
const Roles = () =>
  import(/* webpackChunkName: "roles" */ "views/power/Roles.vue");

const Cate = () =>
  import(/* webpackChunkName: "cate" */ "views/goods/Cate.vue");
const Params = () =>
  import(/* webpackChunkName: "params" */ "views/goods/Params.vue");
const GoodsList = () =>
  import(/* webpackChunkName: "goodsList" */ "views/goods/List.vue");
const Add = () =>
  import(/* webpackChunkName: "add" */ "views/goods/Add.vue");
const Order = () =>
  import(/* webpackChunkName: "order" */ "views/order/Order.vue");
const Report = () =>
  import(/* webpackChunkName: "report" */ "views/report/Report.vue");

Vue.use(VueRouter);

const routes = [
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/home",
    component: Home,
    redirect: "/welcome",
    children: [
      {
        path: "/welcome",
        component: Welcome,
      },
      {
        path: "/users",
        component: Users,
      },
      {
        path: "/users",
        component: Users,
      },
      {
        path: "/rights",
        component: Rights,
      },
      {
        path: "/roles",
        component: Roles,
      },
      {
        path: "/categories",
        component: Cate,
      },
      {
        path: "/params",
        component: Params,
      },
      {
        path: "/goods",
        component: GoodsList,
      },
      {
        path: "/goods/add",
        component: Add,
      },
      {
        path: "/orders",
        component: Order,
      },
      {
        path: "/reports",
        component: Report,
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页，直接放行
  if (to.path === "/login") return next();
  // 从 sessionStorage 中获取到 保存的 token 值
  const tokenStr = window.sessionStorage.getItem("token");
  // 没有token，强制跳转到登录页
  if (!tokenStr) return next("/login");
  next();
});

export default router;
